'use strict'
const dayjs = require('dayjs')
const bcrypt = require('bcryptjs')
// 定义性别枚举
const genderMap = { 0: '保密', 1: '男', 2: '女' }
const formatDate = (date) =>
	date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : date
module.exports = (app) => {
	const { STRING, INTEGER, DATE, VIRTUAL, BOOLEAN } = app.Sequelize
	const User = app.model.define(
		't_user',
		{
			id: {
				type: INTEGER,
				primaryKey: true,
				autoIncrement: true,
				allowNull: true,
			},
			username: STRING(30),
			password: {
				type: STRING,
				// 密码自动加盐
				set(val) {
					const salt = app.config.jwt.secret.secret
					const pwd = bcrypt.hashSync(val, salt)
					// 传入2个参数，第一个是字段名称，第二个是加密字符串
					this.setDataValue('password', pwd)
				},
			},
			status: {
				type: BOOLEAN,
				defaultValue: true,
			},
			avatar: STRING,
			phone: INTEGER,
			gender: INTEGER,
			gender_text: {
				type: VIRTUAL,
				get() {
					const gender = this.getDataValue('gender')
					return genderMap[gender] ? genderMap[gender] : ''
				},
			},
			createdAt: {
				type: DATE,
				get() {
					// 返回修改后的时间
					return formatDate(this.getDataValue('createdAt'))
				},
			},
			updatedAt: {
				type: DATE,
				get() {
					// 返回修改后的时间
					return formatDate(this.getDataValue('updatedAt'))
				},
			},
			deletedAt: {
				type: DATE,
				get() {
					// 返回修改后的时间
					return formatDate(this.getDataValue('deletedAt'))
				},
			},
		},
		{
			tableName: 't_user', //指定表名称
			timestamps: true,
		}
	)

	User.associate = function () {
		User.belongsToMany(app.model.Role, {
			through: app.model.RoleUser,
			foreignKey: 'user_id',
			otherKey: 'role_id',
			as: 'userRoles',
		})
		User.hasMany(app.model.Comment, {
			foreignKey: 'form_uid',
			targetKey: 'id',
			as: 'userComments',
		})
		User.hasMany(app.model.ArticleCollect, {
			foreignKey: 'user_id',
			targetKey: 'id',
			as: 'userCollects',
		})
		User.hasMany(app.model.ArticleLike, {
			foreignKey: 'user_id',
			targetKey: 'id',
			as: 'userLikes',
		})
		User.hasMany(app.model.Article, {
			foreignKey: 'user_id',
			targetKey: 'id',
			as: 'userArticles',
		})
	}

	return User
}
